package com.emergency.controller;

import com.emergency.data.param.UserParam;
import com.emergency.http.DefaultResponseCode;
import com.emergency.http.WrapMapper;
import com.emergency.http.Wrapper;
import com.emergency.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

@Validated
@RestController
@RequestMapping("/user")
@Api(tags = "用户API")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @return Wrapper
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Wrapper<?> login(@ApiParam("用户名") @RequestParam @NotBlank(message = "username 不能为空") String username,
                            @ApiParam("密码") @RequestParam @NotBlank(message = "password 不能为空") String password) {
        return WrapMapper.ok(userService.login(username.trim(), password));
    }

    /**
     * 新增用户
     *
     * @param userParam param
     * @return Wrapper
     */
    @ApiOperation("新增用户")
    @PostMapping("/addUser")
    public Wrapper<?> addUser(@Valid UserParam userParam) {
        return WrapMapper.wrap(userService.addUser(userParam) ?
                DefaultResponseCode.SAVE_SUCCESS : DefaultResponseCode.SAVE_FAIL);
    }

    /**
     * 修改密码
     *
     * @param username 用户名
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return Wrapper
     */
    @ApiOperation("修改密码")
    @PostMapping("/changePassword")
    public Wrapper<?> changePassword(@ApiParam("用户名") @RequestParam @NotBlank(message = "username 不能为空") String username,
                                     @ApiParam("旧密码") @RequestParam @NotBlank(message = "oldPassword 不能为空") String oldPassword,
                                     @ApiParam("新密码") @RequestParam @NotBlank(message = "newPassword 不能为空") String newPassword) {
        userService.changePassword(username, oldPassword, newPassword);
        return WrapMapper.ok();
    }

    /**
     * 删除用户
     *
     * @param id 用户ID
     * @return Wrapper
     */
    @ApiOperation("删除用户")
    @PostMapping("/deleteUser")
    public Wrapper<?> deleteUser(@ApiParam("用户ID") @RequestParam @NotNull(message = "id 不能为空") Long id) {
        return WrapMapper.wrap(userService.deleteUser(id) ?
                DefaultResponseCode.DELETE_SUCCESS : DefaultResponseCode.DELETE_FAIL);
    }
}
